package com.hdax.ssm.shiro;

import com.hdax.ssm.dao.UserInfoDao;
import com.hdax.ssm.entity.UserInfo;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class MyRealm extends AuthorizingRealm {
    @Autowired
    private UserInfoDao userInfoDao ;


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("==========================");
        String zhu = (String) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRole("admin");
        simpleAuthorizationInfo.addRole("user");
        simpleAuthorizationInfo.addStringPermission("user:*:01");
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken ;
        //得到用户名
        String username = token.getUsername() ;
        //1.根据用户名从数据库表中获取用户的密码
        UserInfo userInfo = userInfoDao.getUser(username) ;
        if(userInfo==null){
            //如果return null
            //则会在抛出异常
            return  null ;
        }
        //   SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username,pwd, ByteSource.Util.bytes("Shiro"),"myrealm") ;
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username,userInfo.getPwd(),this.getName()) ;
        return info;
    }
}
